package org.git.movie.config.init;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.io.Serializable;
import java.util.List;

/**
 * Sentinel动态规则扩展
 * 参考文档： https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95
 * @author sqyc
 */
public class DataSourceInitFunc implements Serializable , InitFunc {
    @Override
    public void init() throws Exception {
        try{
            System.out.println("程序启动立即执行这里的代码");
            // remoteAddress 代表 ZooKeeper 服务端的地址
            // path 对应 ZK 中的数据路径
            String remoteAddress = "localhost:2181";
            String path = "/sentinel_rule_config/open_movie_server/flowRule";
              path = "/sentinel_rule_config/open_movie_server";
            ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new ZookeeperDataSource<>(remoteAddress, path, source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {}));
            FlowRuleManager.register2Property(flowRuleDataSource.getProperty());

        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }

    }
}
